package com.dyrnq.seckill.mq.nats;


import cn.hutool.json.JSONUtil;
import com.dyrnq.seckill.mq.MessageVo;
import com.dyrnq.seckill.service.impl.SeckillOrderService;
import io.nats.client.Connection;
import io.nats.client.Dispatcher;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;


@Component
@Slf4j
@RequiredArgsConstructor
@ConditionalOnProperty(value = "queue.impl", havingValue = "nats")
public class NatsListener implements CommandLineRunner {

    private final SeckillOrderService seckillOrderService;
    private final Connection nc;

    private Dispatcher dispatcher;

    @Override
    public void run(String... args) {
        log.info("starting autoconfigure listener with connection " + this.nc);

        this.dispatcher = this.nc.createDispatcher(m -> {
            log.debug("received message on " + m.getSubject() + " with reply to " + m.getReplyTo());
//            if (m.getReplyTo() != null) {
//                nc.publish(m.getReplyTo(), m.getData());
//            }
//            log.info(new String(m.getData()));


            MessageVo msg = JSONUtil.toBean(new String(m.getData()), MessageVo.class);
            log.info("Message GoodsId {} , UserId {}", msg.getGoodsId(), msg.getUserId());
            long goods_id = msg.getGoodsId();
            long user_id = msg.getUserId();

            seckillOrderService.insert(goods_id, user_id);

        });

        String subject = "seckill";
        log.info("subscribing to " + subject);
        this.dispatcher.subscribe(subject, "myConsumerGroup");

    }
}
